<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Grid\BatchRestore;
use App\Admin\Actions\Grid\Restore;
use App\Admin\Repositories\Category;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

class CategoryController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Category(), function (Grid $grid) {

            $grid->showColumnSelector();
            $grid->disableActions();
            $grid->enableDialogCreate();
            $grid->setDialogFormDimensions('800px', '400px');
            $grid->quickSearch('name');

            $grid->quickCreate(function (Grid\Tools\QuickCreate $create) {

                $create->text('name');

                $create->text('description');

            });

            $grid->column('id')
                ->sortable()
                ->hide();

            $grid->column('name')
                ->editable();

            $grid->column('description')
                ->editable();

            $grid->column('topic_count')
                ->display(function () {

                    return '<a href="/admin/topic?category_id=' . $this->id . '" title="分类话题">' . $this->topic_count . '</a>';
                });

            $grid->column('created_at')
                ->sortable()
                ->hide();

            $grid->column('updated_at')
                ->sortable()
                ->hide();


            // 回收站
            $grid->filter(function (Grid\Filter $filter) {
                // 范围过滤器，调用模型的`onlyTrashed`方法，查询出被软删除的数据。
                $filter->scope('trashed', '回收站')->onlyTrashed();
                $filter->like('name');
                $filter->like('description');
            });
            // 行恢复
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                if (request('_scope_') == 'trashed') {
                    $actions->append(new Restore(\App\Models\Category::class));
                }
            });
            // 批量恢复
            $grid->batchActions(function (Grid\Tools\BatchActions $batch) {
                if (request('_scope_') == 'trashed') {
                    $batch->add(new BatchRestore(\App\Models\Category::class));
                }
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Category(), function (Form $form) {

            $id = $form->getKey();

            $form->hidden('id');

            $form->text('name')
                ->required()
                ->minLength(2)
                ->maxLength(50)
                ->rules('required|unique:categories,name,' . $id);

            $form->textarea('description')->rules('max:3');

        });
    }
}
